package org.example.foodhealth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        // 创建 CORS 配置
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        // 设置允许的访问源
        corsConfiguration.setAllowedOriginPatterns(Arrays.asList("*"));

        // 设置允许的请求头
        corsConfiguration.addAllowedHeader("*");

        // 设置允许的请求方法
        corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));

        // 是否允许携带凭证（Cookies、Authorization 等）
        corsConfiguration.setAllowCredentials(true);

        // 设置 CORS 配置的路径
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);

        return new CorsFilter(source);
    }
}
